from django.forms import ModelForm
from mac import models
from mac.forms import bootstrapform

from mac.utils import encrypt


class UserAddForm(bootstrapform.BootStrapForm, ModelForm):
    class Meta:
        model = models.UserInfo
        fields = '__all__'
        exclude = None
        labels = {
            'username': '用户名',
            'fullname': '全名',
            'password': '密码',
            'phone': '手机号',
            'email': '邮箱',
            'role': '角色',
            'superior': '上级',
            'depart_id': '部门',
        }

    def clean_password(self):
        password = self.cleaned_data.get('password')
        return encrypt.md5(password)


class UserEditForm(ModelForm):
    class Meta:
        model = models.UserInfo
        fields = '__all__'
        exclude = ['password']
        labels = {
            'username': '用户名',
            'fullname': '全名',
            'phone': '手机号',
            'email': '邮箱',
            'role': '角色',
            'superior': '上级',
            'depart_id': '部门',
        }

    def __new__(cls, *args, **kwargs):
        for field_name in cls.base_fields:  # 字段都包含在了cls.base_fields中
            filed_obj = cls.base_fields[field_name]
            # 添加属性
            filed_obj.widget.attrs.update({'class': 'form-control'})
        return ModelForm.__new__(cls)
